//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Services.Localization;
namespace DotNetNuke.Modules.Admin.Languages
{
	partial class TimeZoneEditor : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cboLocales.SelectedIndexChanged += new EventHandler(cboLocales_SelectedIndexChanged);
			cmdAddMissing.Click += new EventHandler(cmdAddMissing_Click);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
			cmdUpdate.Click += new EventHandler(cmdUpdate_Click);

			try {
				if (!Page.IsPostBack) {
					Services.Localization.Localization.LocalizeDataGrid(ref dgEditor, this.LocalResourceFile);
					BindList();
					cboLocales.SelectedValue = Services.Localization.Localization.SystemLocale;
					BindGrid(Localization.SystemLocale);
				}
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cboLocales_SelectedIndexChanged(System.Object sender, System.EventArgs e)
		{
			try {
				try {
					if (!File.Exists(Server.MapPath(ResourceFile(Localization.TimezonesFile, cboLocales.SelectedValue)))) {
						File.Copy(Server.MapPath(Localization.TimezonesFile), Server.MapPath(ResourceFile(Localization.TimezonesFile, cboLocales.SelectedValue)));
					}
				} catch {
					UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("Save.ErrorMessage", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
				BindGrid(cboLocales.SelectedValue);
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdUpdate_Click(System.Object sender, System.EventArgs e)
		{
			XmlNode node;
			XmlDocument resDoc = new XmlDocument();
			try {
				resDoc.Load(Server.MapPath(ResourceFile(Localization.TimezonesFile, cboLocales.SelectedValue)));
				foreach (DataGridItem di in dgEditor.Items) {
					if ((di.ItemType == ListItemType.Item || di.ItemType == ListItemType.AlternatingItem))
					{
						TextBox ctl = (TextBox)di.Cells[0].Controls[1];
						node = resDoc.SelectSingleNode("//root/timezone[@key='" + di.Cells[1].Text + "']");
						node.Attributes["name"].Value = ctl.Text;
					}
				}
				try {
					File.SetAttributes(Server.MapPath(ResourceFile(Localization.TimezonesFile, cboLocales.SelectedValue)), FileAttributes.Normal);
					resDoc.Save(Server.MapPath(ResourceFile(Localization.TimezonesFile, cboLocales.SelectedValue)));
					BindGrid(cboLocales.SelectedValue);
				} catch {
					UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("Save.ErrorMessage", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
				}
				Response.Redirect(Common.Globals.NavigateURL());
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdCancel_Click(System.Object sender, System.EventArgs e)
		{
			try {
				Response.Redirect(Common.Globals.NavigateURL());
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdAddMissing_Click(System.Object sender, System.EventArgs e)
		{
			XmlDocument resDoc = new XmlDocument();
			XmlDocument defDoc = new XmlDocument();
			resDoc.Load(Server.MapPath(ResourceFile(Localization.TimezonesFile, cboLocales.SelectedValue)));
			defDoc.Load(Server.MapPath(Localization.TimezonesFile));
			foreach (XmlNode node in defDoc.SelectNodes("//root/timezone")) {
				if (resDoc.SelectSingleNode("//root/timezone[@key='" + node.Attributes["key"].Value + "']") == null) {
					resDoc.SelectSingleNode("//root").AppendChild(resDoc.ImportNode(node, true));
				}
			}
			try {
				resDoc.Save(Server.MapPath(ResourceFile(Localization.TimezonesFile, cboLocales.SelectedValue)));
				BindGrid(cboLocales.SelectedValue);
			} catch {
				UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("Save.ErrorMessage", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
			}
		}
		private void BindList()
		{
			cboLocales.DataSource = Localization.GetLocales(Null.NullInteger).Values;
			cboLocales.DataBind();
		}
		private void BindGrid(string language)
		{
			DataSet ds = new DataSet();
			DataSet dsDef = new DataSet();
			DataTable dt;
			DataTable dtDef;
			ds.ReadXml(Server.MapPath(ResourceFile(Localization.TimezonesFile, language)));
			ds.Tables[0].TableName = "Resource";
			dt = ds.Tables["Resource"];
			dsDef.ReadXml(Server.MapPath(Localization.TimezonesFile));
			dtDef = dsDef.Tables[0].Copy();
			dtDef.TableName = "Default";
			dtDef.Columns["name"].ColumnName = "defaultvalue";
			ds.Tables.Add(dtDef);
			try {
				pnlMissing.Visible = false;
				ds.Relations.Add("missing", dt.Columns["key"], dtDef.Columns["key"]);
			} catch {
				pnlMissing.Visible = true;
			} finally {
				ds.Relations.Remove("missing");
			}
			try {
				ds.Relations.Add("defaultvalues", dtDef.Columns["key"], dt.Columns["key"]);
			} catch {
				DeleteEntries(ResourceFile(Localization.TimezonesFile, language), Services.Localization.Localization.TimezonesFile);
				ds.Relations.Remove("defaultvalues");
				ds = new DataSet();
				dsDef = new DataSet();
				ds.ReadXml(Server.MapPath(ResourceFile(Localization.TimezonesFile, language)));
				ds.Tables[0].TableName = "Resource";
				dt = ds.Tables["Resource"];
				dsDef.ReadXml(Server.MapPath(Localization.TimezonesFile));
				dtDef = dsDef.Tables[0].Copy();
				dtDef.TableName = "Default";
				dtDef.Columns["name"].ColumnName = "defaultvalue";
				ds.Tables.Add(dtDef);
				ds.Relations.Add("defaultvalues", dtDef.Columns["key"], dt.Columns["key"]);
			}
			dgEditor.DataSource = ds;
			dgEditor.DataMember = "Resource";
			dgEditor.DataBind();
		}
		private void DeleteEntries(string resourceFile, string defaultFile)
		{
			XmlNode parent;
			XmlDocument resDoc = new XmlDocument();
			XmlDocument defDoc = new XmlDocument();
			resDoc.Load(Server.MapPath(resourceFile));
			defDoc.Load(Server.MapPath(defaultFile));
			foreach (XmlNode node in resDoc.SelectNodes("//root/timezone")) {
				if (defDoc.SelectSingleNode("//root/timezone[@key='" + node.Attributes["key"].Value + "']") == null) {
					parent = node.ParentNode;
					parent.RemoveChild(node);
				}
			}
			try {
				resDoc.Save(Server.MapPath(resourceFile));
			} catch {
				UI.Skins.Skin.AddModuleMessage(this, Services.Localization.Localization.GetString("Save.ErrorMessage", this.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning);
			}
		}
		private string ResourceFile(string filename, string language)
		{
			if (language == Services.Localization.Localization.SystemLocale) {
				return filename;
			} else {
				return filename.Substring(0, filename.Length - 4) + "." + language + ".xml";
			}
		}
	}
}
